/**
 * ReportGear(2011)
 */
package com.reportgear.report.parameter.model;

import java.awt.Dimension;

import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import org.dom4j.Element;

import com.reportgear.core.api.NameObject;
import com.reportgear.core.api.XmlSerializer;
import com.sot.core.util.StringUtils;

/**
 * 报表核心-参数-模型
 * 
 * @version 1.0 2011-4-11
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class Parameter extends NameObject<Object> implements XmlSerializer {
	// 标签
	private String caption = "";

	public Parameter(String name) {
		this(name, "", null);
	}

	public Parameter(String name, String caption, Object value) {
		super(name, value);

		this.caption = caption;
	}

	/**
	 * 获取输入组件
	 * 
	 * @return 输入组件
	 */
	public JComponent getInputComponent() {
		final JTextField c = new JTextField();
		c.getDocument().addDocumentListener(new DocumentListener() {

			@Override
			public void changedUpdate(DocumentEvent e) {
				Parameter.this.setObject(c.getText());
			}

			@Override
			public void insertUpdate(DocumentEvent e) {
				Parameter.this.setObject(c.getText());
			}

			@Override
			public void removeUpdate(DocumentEvent e) {
				Parameter.this.setObject(c.getText());
			}
		});

		c.setPreferredSize(new Dimension(200, 24));

		return c;
	}

	@Override
	public String toString() {
		return this.caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	public String getCaption() {
		if (StringUtils.isEmpty(caption)) {
			return this.name;
		} else {
			return caption;
		}
	}

	@Override
	public void read(Element parent) {
		Element el = parent.element("caption");
		this.setCaption(el.getTextTrim());

		el = parent.element("name");
		this.setName(el.getTextTrim());
	}

	@Override
	public void write(Element parent) {
		Element el = parent.addElement("caption");
		el.addText(this.caption);

		el = parent.addElement("name");
		el.addText(this.name);
	}
}
